package com.thinkgsp.webapp.controller.inv;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thinkgsp.jxc.model.Inventory;
import com.thinkgsp.jxc.model.InventoryAdd;
import com.thinkgsp.jxc.model.Product;
import com.thinkgsp.jxc.model.ProductBatchNo;
import com.thinkgsp.jxc.service.InventoryAddService;
import com.thinkgsp.jxc.service.InventoryService;
import com.thinkgsp.jxc.service.ProductBatchNoService;
import com.thinkgsp.jxc.service.ProductContactService;
import com.thinkgsp.jxc.service.ProductService;
import com.thinkgsp.sys.model.SysAccountPeriod;
import com.thinkgsp.sys.model.SysUser;
import com.thinkgsp.webapp.controller.BaseController;
import com.thinkgsp.webapp.util.ExportExcel;
import com.thinkgsp.webapp.util.ExtReturn;

@Controller
@RequestMapping(value = "/inv")
public class InventoryController extends BaseController {
	@Autowired
	private InventoryService inventoryService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductBatchNoService productBatchNoService;
	
	@Autowired
	private InventoryAddService inventoryAddService;
	
	@Autowired
	private ProductContactService productContactService;
	
	//查询产品库存 @param{}:val:产品搜索条件
	@RequestMapping("/invsearch.do")
    @ResponseBody
    public Object  invsearch(HttpServletRequest request,
			HttpServletResponse response){
		try {
			String val=request.getParameter("val");
			if(StringUtils.isBlank(val)) return new ExtReturn(false,"条件不能为空");
			int limit = Integer.parseInt(request.getParameter("limit"));
			int start = Integer.parseInt(request.getParameter("start"));
			SysAccountPeriod period=this.inventoryService.getCurrentPeriod();
			String invAddId=request.getParameter("invAddId");
			if(StringUtils.isBlank(invAddId))
				return this.inventoryService.searchInventory(period.getFyear(),period.getPeriod(), val,start,limit);
			else{
				return this.inventoryService.searchInventory(period.getFyear(), period.getPeriod(),Integer.decode(invAddId), val,start,limit);
			}
		}catch(Exception e){
			return new ExtReturn(false,"查询存货信息出错",e);
		}
	}
	//根据存货地点查库存  @param{}:val:查询条件[val|all] ,invAddId:库房ID 
	@RequestMapping("/searchInventory.do")
    @ResponseBody
    public Object  searchInventory(HttpServletRequest request,
			HttpServletResponse response){
		try {
			String val=request.getParameter("val");
			if(StringUtils.isBlank(val)) return new ExtReturn(false,"条件不能为空");
			int limit = Integer.parseInt(request.getParameter("limit"));
			int start = Integer.parseInt(request.getParameter("start"));
			SysAccountPeriod period=this.inventoryService.getCurrentPeriod();
			
			if("all".equals(val)){
				return this.inventoryService.getInventoryList(period.getFyear(), period.getPeriod(),start,limit);
			}else{
				return this.inventoryService.searchInventory(period.getFyear(), period.getPeriod(), val,start,limit);
			}
		}catch(Exception e){
			return new ExtReturn(false,"查询存货信息出错",e);
		}
	}
	
	@RequestMapping("/searchByInvAdd.do")
    @ResponseBody
    public Object  searchByInvAdd(@RequestParam Integer invAddId,@RequestParam Integer limit,@RequestParam Integer start){
		try {
			SysAccountPeriod period=this.inventoryService.getCurrentPeriod();
			
			return this.inventoryService.getInventoryListByInvAdd(period.getFyear(), period.getPeriod(),invAddId,start,limit);
		}catch(Exception e){
			return new ExtReturn(false,"查询存货信息出错",e);
		}
	}
	
	//根据商品类型查库存  @param{}: invAddId:库房ID,classifyId:商品类型
	@RequestMapping("/searchInvByClassify.do")
    @ResponseBody
    public Object  searchInvByInvClassify(@RequestParam Integer classifyId,@RequestParam Integer limit,@RequestParam Integer start){
		try {

			SysAccountPeriod period=this.inventoryService.getCurrentPeriod();
			return this.inventoryService.getInventoryList(period.getFyear(), period.getPeriod(),classifyId,start,limit);
		}catch(Exception e){
			return new ExtReturn(false,"查询存货信息出错",e);
		}
	}
	
	@RequestMapping("/invaddnew.do")
    @ResponseBody
    public Object  invAddNewProduct(HttpServletRequest request,
			HttpServletResponse response){
		try {
			
			String invAddIdstr=request.getParameter("invAddId");
			if(StringUtils.isBlank(invAddIdstr)) return new ExtReturn(false,"存货地点不能为空");
			
			String prodIdstr=request.getParameter("prodId");
			if(StringUtils.isBlank(prodIdstr)) return new ExtReturn(false,"商品不能为空");
			Product product=this.productService.getProduct(Integer.decode(prodIdstr));
			
			String batchNoIdstr=request.getParameter("batchNoId");
			if(StringUtils.isBlank(batchNoIdstr)) return new ExtReturn(false,"批号不能为空");
			
			ProductBatchNo batchNo=this.productBatchNoService.getBatchNo(Long.decode(batchNoIdstr));
			InventoryAdd invAdd=this.inventoryAddService.getInventoryAdd(Integer.decode(invAddIdstr));
			return new ExtReturn(true,"成功添加库存商品",this.inventoryService.InitProductInventory(product, batchNo, invAdd));
		}catch(Exception e){
			loger.error(e.getMessage());
			return new ExtReturn(false,"添加库存商品信息出错",e);
		}
	}
	//修改库存状态  @param{}: invId: 库存ID,state:状态[0|1]
	@RequestMapping("/invupdstate.do")
    @ResponseBody
    public Object  invUpdateState(HttpServletRequest request,
			HttpServletResponse response){
		try {
			String invIdstr=request.getParameter("invId");
			if(StringUtils.isBlank(invIdstr)) return new ExtReturn(false,"库存ID不能为空");
			String  statestr=request.getParameter("state");
			if(StringUtils.isBlank(statestr)) return new ExtReturn(false,"状态不能为空");
				
			this.inventoryService.updateState(Long.decode(invIdstr),Integer.decode(statestr));
			return new ExtReturn(true,"修改库存状态成功");
		}catch(Exception e){
			loger.error(e.getMessage());
			return new ExtReturn(false,"修改库存状态出错",e);
		}
	}
	
	//获取产品所有批号 @param{}: prodId: 产品ID
	@RequestMapping("/getprodbatchno.do")
    @ResponseBody
    public Object  getProductBatchNo(HttpServletRequest request,
			HttpServletResponse response){
		try {
			String idstr=request.getParameter("prodId");
			if(StringUtils.isBlank(idstr)) return new ExtReturn(false,"商品ID不能为空");
			return this.productBatchNoService.getBatchNo(Integer.decode(idstr));
		}catch(Exception e){
			return new ExtReturn(false,"查询产品批号出错",e);
		}
	}
	//获取产品所有批号 @param{}: prodId: 产品ID
	@RequestMapping("/getdefaultbatchno.do")
    @ResponseBody
    public Object  getDefaultBatchNo(HttpServletRequest request,
			HttpServletResponse response){
		try {
			String idstr=request.getParameter("prodId");
			if(StringUtils.isBlank(idstr)) return new ExtReturn(false,"商品ID不能为空");
			return this.productBatchNoService.getBatchNo(Integer.decode(idstr),ProductBatchNo.NON_BATCH_MGR_VALUE);
		}catch(Exception e){
			return new ExtReturn(false,"查询产品批号出错",e);
		}
	}
		
	@RequestMapping(value = "/updprodbatchno.do",method = RequestMethod.POST )
	@ResponseBody
	public Object updProdManuf(Model model ,@RequestBody ProductBatchNo batch) {
		try {
			if(batch!=null){
				Product product=this.productService.getProduct(batch.getProductId());
				if(!product.isBatchMgr()) return new ExtReturn(false,"非批号管理商品,不需要添加批号");
				this.productBatchNoService.saveBatchNo(batch);
				return new ExtReturn(true,"添加或修改批号成功");
			}else{
				return new ExtReturn(false,"未获取批号相关信息");
			}
		} catch (Exception e) {
			loger.error(e.getMessage());
			return new ExtReturn(false,"添加或修改批号出错",e);
		}	
	}
	
   //删除零库存商品 @param{}: invId: 库存ID
	@RequestMapping("/delInvZero.do")
    @ResponseBody
    public Object  delInvProductZero(HttpServletRequest request,
			HttpServletResponse response){
		try {
			String idstr=request.getParameter("invId");
			if(StringUtils.isBlank(idstr)) return new ExtReturn(false,"库存内码不能为空");
			this.inventoryService.deleteInventory(Long.decode(idstr));
			return new ExtReturn(true,"删除零库存商品成功");
		}catch(Exception e){
			return new ExtReturn(false,"删除零库存商品出错",e);
		}
	}
	
	//删除零库存商品 @param{}: begPeriod : 开始期间2013.02, endPeriod 结束期间2013.12, invAddId 存货地址, productId 商品内码, batchNoId 批号内码
	@RequestMapping("/invflowquery.do")
	@ResponseBody
	public Object  invFlowQuery(@RequestParam("begPeriod")BigDecimal begPeriod,
								@RequestParam("endPeriod")BigDecimal endPeriod,
								@RequestParam("productId")Integer productId,
								@RequestParam("batchNoId")Long batchNoId,
								@RequestParam("invAddId")Integer invAddId){
		try {
			if(begPeriod == null) return new ExtReturn(false,"开始期间不能为空!");
			if(endPeriod == null) return new ExtReturn(false,"截止期间不能为空!");
			if(productId == null || productId == 0) return new ExtReturn(false,"商品不能为空!");
			return this.productContactService.getProductContactList(begPeriod, endPeriod, invAddId,productId,batchNoId);
		}catch(Exception e){
			loger.error(e.getMessage(), e);
			return new ExtReturn(false,"查询商品出入库流水出错",e);
		}
	}
	@RequestMapping("/invflowquerybydate.do")
	@ResponseBody
	public Object  invFlowQueryByDate(HttpServletRequest request,
			HttpServletResponse response){
		try {
			String idstr=request.getParameter("productId");
			if(StringUtils.isBlank(idstr)) return new ExtReturn(false,"商品不能为空");
			String invAddIdstr=request.getParameter("invAddId");
			if(StringUtils.isBlank(invAddIdstr)) return new ExtReturn(false,"存货地点不能为空");
			String begdatestr=request.getParameter("begDate");
			if(StringUtils.isBlank(begdatestr)) return new ExtReturn(false,"开始时间不能为空");
			String enddatestr=request.getParameter("endDate");
			if(StringUtils.isBlank(enddatestr)) return new ExtReturn(false,"结束时间不能为空");
			String batnostr=request.getParameter("batchNoId");
			if(StringUtils.isBlank(batnostr)) return new ExtReturn(false,"批号不能为空");
			return this.productContactService.getProductContactList(java.sql.Date.valueOf(begdatestr),java.sql.Date.valueOf(enddatestr), Integer.decode(invAddIdstr),Integer.decode(idstr),Long.decode(batnostr));
		}catch(Exception e){
			loger.error(e.getMessage(), e);
			return new ExtReturn(false,"查询商品出入库流水出错",e);
		}
	}
	@RequestMapping("/getInvAdd.do")
    @ResponseBody
    public Object  getInvAdd(HttpServletRequest request,
			HttpServletResponse response){
		try{
			String val=request.getParameter("val");
			if(!StringUtils.isBlank(val) || "all".equals(val)){
				return this.inventoryAddService.getAllInventoryAdd();
			}
			SysUser user = (SysUser) SecurityContextHolder.getContext()
				    .getAuthentication()
				    .getPrincipal();
			return  this.inventoryAddService.getInventoryAddByDept(user.getLogonDept().getDeptId());
		}catch(Exception e){
			return new ExtReturn(false,"获取货位出错",e);
		}		 
	}
	/*
	 * 数据导出
	 */
	@RequestMapping("/getXLS.do")
    public void  getXLS(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		try{
			String classifyId=request.getParameter("classifyId");
			if(StringUtils.isBlank(classifyId)) classifyId="1";
			response.setContentType("octets/stream");
	        response.addHeader("Content-Disposition","attachment;filename="+ new String(("库存数据").getBytes("GB2312"),"iso8859-1")+".xls");
			SysAccountPeriod period=this.inventoryService.getCurrentPeriod();
			List<Inventory>  inv= this.inventoryService.getInventoryList(period.getFyear(), period.getPeriod(),Integer.parseInt(classifyId));
			OutputStream out = response.getOutputStream();
	        ExportExcel<Inventory> ex = new ExportExcel<Inventory>();
	        HSSFWorkbook book=ex.exportExcelByFieldAnnotation(inv);
	        book.write(out);
		}catch(Exception e){
			response.getWriter().write("数据导出出错");			
		}		 
	}
}
